package com.shajj.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

public class WebController extends VelocityViewServlet {

	private static final long serialVersionUID = -5557022672719034632L;

	private Map<String, WebAction> actionMap = new HashMap<String, WebAction>();

	@Override
	protected void fillContext(Context context, HttpServletRequest request) {
		String requestURI = request.getServletPath();
		WebAction action = getAction(requestURI);
		if (action == null) {
			return;
		}
		action.handleRequest(context, request);
		super.fillContext(context, request);
	}

	private WebAction getAction(String uri) {
		if (uri.startsWith("/")) {
			uri = uri.substring(1);
		}
		uri = uri.replace(".htm", "");
		if (uri == null || "".equals(uri)) {
			return null;
		}
		uri = uri.substring(0, 1).toUpperCase() + uri.substring(1);
		WebAction action = actionMap.get(uri);
		if (action == null) {
			try {
				action = (WebAction)Class.forName("com.shajj.web.action." + uri + "Action").newInstance();
				actionMap.put(uri, action);
			} catch (Exception e) {
			}
		}
		return action;
	}

	@Override
	protected Template getTemplate(HttpServletRequest request, HttpServletResponse response) {
		String requestURI = request.getServletPath();
		return getTemplate(requestURI.replace(".htm", ".vm"));
	}

}
